package com.whccb.apps.office.document.at;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.commons.at.AbstExpression;
import com.actionsoft.bpms.commons.at.ExpressionContext;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.whccb.apps.office.document.util.ODAppUtil;

/**
 * 
 * 根据用户帐号（精确匹配权限）及文种名称(模糊匹配)查询符合条件的文种，只会返回一个文种信息
 * 
 * @author xqli
 * 
 */
public class GetOfficeDocumentTypeInfoByUidAndLikeName extends AbstExpression {
	public GetOfficeDocumentTypeInfoByUidAndLikeName(
			ExpressionContext atContext, String expressionValue) {
		super(atContext, expressionValue);
	}

	public String execute(String expression) {
		String uid = getParameter(expression, 1).trim();// 用户帐号
		String likeTypeName = getParameter(expression, 2).trim();// 文种名称
		String field = getParameter(expression, 3).trim();// 返回的字段名称

		UserContext user = UserContext.fromUID(uid);
		if (user != null) {
			String inWhere = ODAppUtil.getUserDeptSqlInWhere(null, user
					.getDepartmentModel().getId());
			String querySql = " SELECT * FROM BO_WHBK_OD_RECORDTYPE WHERE USESCOPEID in "
					+ inWhere;
			List<Map<String, String>> odRecordTypeBoList = DBSql.query(
					querySql, new RowMapper<Map<String, String>>() {
						@Override
						public Map<String, String> mapRow(ResultSet rs,
								int rowNum) throws SQLException {
							Map<String, String> map = new HashMap<String, String>();
							map.put("ID", rs.getString("ID"));
							map.put("CODE", rs.getString("CODE"));
							map.put("NAME", rs.getString("NAME"));
							map.put("FILEFROM", rs.getString("FILEFROM"));
							return map;
						}
					});
			if (odRecordTypeBoList != null && !odRecordTypeBoList.isEmpty()
					&& odRecordTypeBoList.size() > 0) {
				for (Map<String, String> map : odRecordTypeBoList) {
					if (map != null && !map.isEmpty()
							&& map.get("NAME") != null) {
						if (map.get("NAME").contains(likeTypeName)) {
							Set<String> keySet = map.keySet();
							for (String key : keySet) {
								if (StringUtils.isNotEmpty(key)
										&& key.toUpperCase().equals(
												field.toUpperCase())) {
									return map.get(key);
								}
							}
						}
					}
				}
			}

		}
		return "";
	}
}
